import axios from 'axios'

// 创建 axios 实例 - 使用代理路径
export const orthancApi = axios.create({
  // 改用代理URL
  baseURL: '/api',
  auth: {
    username: 'orthanc',
    password: 'orthanc123'
  },
  timeout: 30000
})

export default {
  // 获取所有患者
  async getPatients() {
    try {
      const response = await orthancApi.get('/patients');
      
      if (Array.isArray(response.data)) {
        // 获取每个患者的详细信息
        const patientsDetails = [];
        
        for (const patientId of response.data) {
          try {
            // 获取患者详细信息
            const patientData = await orthancApi.get(`/patients/${patientId}`);
            
            // 获取患者的所有研究ID
            const studiesResponse = await orthancApi.get(`/patients/${patientId}/studies`);
            let studies = [];
            
            if (Array.isArray(studiesResponse.data) && studiesResponse.data.length > 0) {
              // 确保我们处理的是字符串ID数组
              const studyIds = studiesResponse.data.map(study => {
                // 如果是对象，提取ID
                if (typeof study === 'object' && study !== null && study.ID) {
                  return study.ID;
                }
                // 如果是字符串，直接使用
                return study;
              });
              
              // 获取每个研究的详细信息
              for (const studyId of studyIds) {
                try {
                  const studyData = await orthancApi.get(`/studies/${studyId}`);
                  studies.push(studyData.data);
                } catch (error) {
                  console.error(`获取研究 ${studyId} 详情失败:`, error);
                }
              }
            }
            
            // 按日期排序研究（最新的在前面）
            studies.sort((a, b) => {
              const dateA = a.MainDicomTags.StudyDate || '19000101';
              const dateB = b.MainDicomTags.StudyDate || '19000101';
              return dateB.localeCompare(dateA);
            });
            
            // 构建患者对象
            const patient = {
              id: patientId,
              name: patientData.data.MainDicomTags.PatientName || 'Unknown',
              birthDate: patientData.data.MainDicomTags.PatientBirthDate || 'Unknown',
              sex: patientData.data.MainDicomTags.PatientSex || 'Unknown',
              studiesCount: studies.length,
              lastStudyDate: studies.length > 0 ? studies[0].MainDicomTags.StudyDate : 'Unknown',
              studies: studies
            };
            
            patientsDetails.push(patient);
          } catch (error) {
            console.error(`获取患者 ${patientId} 详情失败:`, error);
          }
        }
        
        return patientsDetails;
      }
      
      return [];
    } catch (error) {
      console.error('获取患者列表失败:', error);
      throw error;
    }
  },
  
  // 获取患者的研究
  async getStudies(patientId) {
    console.log('Getting studies for patient:', patientId);
    try {
      const response = await orthancApi.get(`/patients/${patientId}/studies`);
      console.log('Raw studies response:', response);
      
      // 检查是否有有效数据
      if (!response.data) {
        console.error('No data in response');
        return [];
      }
      
      // 规范化响应 - 确保返回包含ID的字符串数组
      if (Array.isArray(response.data)) {
        // 如果是数组，检查每个元素的类型
        const normalizedStudies = response.data.map(study => {
          if (typeof study === 'string') {
            return study;
          } else if (typeof study === 'object' && study !== null) {
            // 如果是对象，尝试提取ID
            return study.ID || study.id || Object.keys(study)[0];
          }
          return null;
        }).filter(id => id !== null);
        
        console.log('Normalized studies:', normalizedStudies);
        return normalizedStudies;
      } else {
        console.error('Unexpected response format:', response.data);
        return [];
      }
    } catch (error) {
      console.error('Error fetching studies:', error);
      return [];
    }
  },
  
  // 获取研究的序列
  async getSeries(studyId) {
    console.log('Getting series for study:', studyId);
    
    // 确保 studyId 是字符串
    if (typeof studyId !== 'string') {
      console.error('Invalid studyId:', studyId);
      
      // 尝试从对象中提取ID
      if (studyId && typeof studyId === 'object') {
        const extractedId = studyId.ID || studyId.id;
        if (extractedId && typeof extractedId === 'string') {
          console.log('从对象中提取ID:', extractedId);
          studyId = extractedId;
        } else {
          throw new Error('Invalid studyId');
        }
      } else {
        throw new Error('Invalid studyId');
      }
    }
    
    try {
      const response = await orthancApi.get(`/studies/${studyId}/series`);
      console.log('Series response:', response.data);
      return response.data;
    } catch (error) {
      console.error('获取序列失败:', error);
      throw error;
    }
  },
  
  // 获取序列的实例
  async getInstances(seriesId) {
    console.log('获取序列的实例:', seriesId);
    
    // 确保 seriesId 是字符串
    if (typeof seriesId !== 'string') {
      console.error('Invalid seriesId:', seriesId);
      
      // 尝试从对象中提取ID
      if (seriesId && typeof seriesId === 'object') {
        const extractedId = seriesId.ID || seriesId.id;
        if (extractedId && typeof extractedId === 'string') {
          console.log('从对象中提取seriesId:', extractedId);
          seriesId = extractedId;
        } else {
          throw new Error('Invalid seriesId');
        }
      } else {
        throw new Error('Invalid seriesId');
      }
    }
    
    try {
      const response = await orthancApi.get(`/series/${seriesId}/instances`);
      console.log('实例响应:', response.data);
      return response.data;
    } catch (error) {
      console.error('获取实例失败:', error);
      return [];
    }
  },
  
  // 获取序列的实例
  async getInstancesForSeries(seriesId) {
    console.log('Getting instances for series:', seriesId);
    
    try {
      // 检查是否已经有实例数据
      if (seriesId && typeof seriesId === 'object' && seriesId.Instances) {
        console.log('使用已有的实例数据');
        return seriesId.Instances;
      }
      
      // 获取序列的实例ID列表
      const response = await orthancApi.get(`/series/${seriesId}/instances`);
      console.log('Instances response:', response.data);
      
      // 检查响应格式
      if (Array.isArray(response.data)) {
        // 如果是对象数组而不是字符串ID数组，直接返回
        if (response.data.length > 0 && typeof response.data[0] === 'object') {
          return response.data;
        }
        
        // 获取每个实例的详细信息
        const instanceDetails = [];
        for (const instanceId of response.data) {
          if (typeof instanceId === 'string') {
            const instanceData = await orthancApi.get(`/instances/${instanceId}`);
            instanceDetails.push(instanceData.data);
          }
        }
        
        return instanceDetails;
      } else {
        return [];
      }
    } catch (error) {
      console.error('获取实例失败:', error);
      throw error;
    }
  },
  
  // 上传DICOM文件
  async uploadDicom(file) {
    const formData = new FormData()
    formData.append('dicom', file)
    
    try {
      const response = await orthancApi.post('/instances', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      return { success: true, data: response.data }
    } catch (error) {
      return { success: false, error: error.response?.data || error.message }
    }
  },
  
  // 获取DICOM文件的图像帧
  getDicomFrameUrl(instanceId, frameIndex = 0) {
    // 这里使用绝对路径，因为会直接在浏览器URL栏使用
    return `/api/instances/${instanceId}/frames/${frameIndex}/rendered`
  },
  
  // 保存标注数据
  async saveAnnotations(studyId, annotations) {
    try {
      await orthancApi.put(`/studies/${studyId}/attachments/annotations`, JSON.stringify(annotations), {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      return { success: true }
    } catch (error) {
      return { success: false, error: error.message }
    }
  },
  
  // 获取患者信息
  async getPatientInfo(patientId) {
    // console.log('获取患者信息:', patientId);
    
    try {
      const response = await orthancApi.get(`/patients/${patientId}`);
      // console.log('患者信息响应:', response.data);
      
      return {
        id: patientId,
        name: response.data.MainDicomTags?.PatientName || 'Unknown',
        birthDate: response.data.MainDicomTags?.PatientBirthDate || 'Unknown',
        sex: response.data.MainDicomTags?.PatientSex || 'Unknown'
      };
    } catch (error) {
      console.error('获取患者信息失败:', error);
      return {
        id: patientId,
        name: 'Unknown',
        birthDate: 'Unknown',
        sex: 'Unknown'
      };
    }
  },
  
  // 获取研究的序列
  async getStudySeries(studyId) {
    console.log('Getting series for study:', studyId);
    
    try {
      // 获取研究的序列ID列表
      const response = await orthancApi.get(`/studies/${studyId}/series`);
      console.log('Series response:', response.data);
      
      // 检查响应格式
      if (Array.isArray(response.data) && response.data.length > 0) {
        // 如果是数组对象而不是字符串ID数组，直接返回
        if (typeof response.data[0] === 'object') {
          return response.data;
        }
        
        // 获取每个序列的详细信息
        const seriesDetails = [];
        for (const seriesId of response.data) {
          // 确保seriesId是字符串
          if (typeof seriesId === 'string') {
            const seriesData = await orthancApi.get(`/series/${seriesId}`);
            seriesDetails.push(seriesData.data);
          } else {
            console.error('非字符串序列ID:', seriesId);
          }
        }
        
        return seriesDetails;
      } else {
        return [];
      }
    } catch (error) {
      console.error('获取序列失败:', error);
      throw error;
    }
  },
  
  // 获取DICOM文件URL
  getDicomUrl(instanceId) {
    // 处理各种类型的实例ID
    let id = instanceId;
    
    // 如果是对象，尝试提取ID
    if (instanceId && typeof instanceId === 'object') {
      id = instanceId.ID || instanceId.id;
    }
    
    // 如果是字符串数组的第一个元素，提取它
    if (Array.isArray(instanceId) && instanceId.length > 0) {
      id = instanceId[0];
      // 如果数组元素是对象，再次尝试提取ID
      if (typeof id === 'object') {
        id = id.ID || id.id;
      }
    }
    
    // 确保我们有一个有效的字符串ID
    if (!id || typeof id !== 'string') {
      console.error('无效的实例ID:', instanceId);
      return '';
    }
    
    // 返回DICOM文件URL
    return `/api/instances/${id}/file`;
  },
  
  // 获取患者的所有检查
  async getPatientStudies(patientId) {
    try {
      // 获取患者的检查ID列表
      const response = await orthancApi.get(`/patients/${patientId}/studies`);
      
      // 检查响应格式
      if (Array.isArray(response.data) && response.data.length > 0) {
        // 获取每个检查的详细信息
        const studyDetails = [];
        for (const studyId of response.data) {
          // 确保studyId是字符串
          if (typeof studyId === 'string') {
            const studyData = await orthancApi.get(`/studies/${studyId}`);
            studyDetails.push(studyData.data);
          } else if (typeof studyId === 'object' && studyId.ID) {
            // 如果已经是对象，直接添加
            studyDetails.push(studyId);
          }
        }
        
        return studyDetails;
      } else {
        return [];
      }
    } catch (error) {
      console.error('获取患者检查失败:', error);
      throw error;
    }
  },
  
  // 删除患者
  async deletePatient(patientId) {
    try {
      await orthancApi.delete(`/patients/${patientId}`);
      return { success: true };
    } catch (error) {
      console.error('删除患者失败:', error);
      return { 
        success: false, 
        error: error.response?.data?.Message || error.message 
      };
    }
  }
} 